import React, {useEffect, useRef} from 'react';
import styled from 'styled-components';
import gsap from 'gsap';

const ImageContainer = styled.div`
    margin: 0 auto;
    display: grid;
    cursor: pointer;
    position: relative;
    width: 60vw;
    height: 40vh;
    background-size: cover;
    background-position: 50% 50%;
    border: 1px solid black;
    border-radius: inherit;
    transform-origin: ${({$origin}) => $origin || '50% 50%'};
`;

const ImageElement = styled.div`
    transform-origin: inherit;
    position: relative;
    grid-area: 1 / 1 / 2 / 2;
    width: 100%;
    height: 100%;
    will-change: transform;
    border-radius: inherit;
    background-size: inherit;
    background-position: inherit;
    border: inherit;
    background-image: url(${({$bgImage}) => $bgImage});
`;

const ImageHoverFilter = ({
                              imageUrl,
                              repetitionCount = 10,
                              duration = 0.5,
                              ease = 'power2.inOut',
                              stagger = 0,
                              scaleInterval = 0.05,
                              rotationInterval = 4,
                              transformOrigin = '50% 50%',
                          }) => {
    const containerRef = useRef(null);
    const elementRefs = useRef([]);
    const timelineRef = useRef(null);

    useEffect(() => {
        const elements = elementRefs.current;
        if (!containerRef.current || elements.length === 0) return;

        gsap.set(containerRef.current, {backgroundImage: 'none'});
        gsap.set(containerRef.current, {transformOrigin});

        timelineRef.current = gsap.timeline({paused: true}).to(elements, {
            scale: (i) => Math.max(1 - scaleInterval * i, 0),
            rotation: (i) => i * rotationInterval,
            duration,
            ease,
            stagger,
        });

        const onMouseEnter = () => timelineRef.current.play();
        const onMouseLeave = () => timelineRef.current.reverse();

        const container = containerRef.current;
        container.addEventListener('mouseenter', onMouseEnter);
        container.addEventListener('mouseleave', onMouseLeave);

        return () => {
            container.removeEventListener('mouseenter', onMouseEnter);
            container.removeEventListener('mouseleave', onMouseLeave);
        };
    }, [duration, ease, stagger, scaleInterval, rotationInterval, transformOrigin]);

    return (
        <ImageContainer
            ref={containerRef}
            style={{backgroundImage: `url(${imageUrl})`}}
            $origin={transformOrigin}
        >
            {[...Array(Math.max(2, repetitionCount))].map((_, i) => (
                <ImageElement
                    key={i}
                    $bgImage={imageUrl}
                    ref={(el) => (elementRefs.current[i] = el)}
                />
            ))}
        </ImageContainer>
    );
};

export default ImageHoverFilter;
